<template>
	<view class="sg-choose-image">
		<u-upload
			:fileList="fileList1"
			@afterRead="afterRead"
			@delete="deletePic"
			name="1"

			:maxCount="1"
			:previewFullImage="true"
		/>
		<u-line />
		<slot />
	</view>
</template>

<script>
import { getToken } from '@/store/user'

export default {
  data() {
    return {
      fileList1: [],
      picUrl: '',
      canset: false
    }
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this[ `fileList${ event.name }` ].splice(event.index, 1)
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      const lists = [].concat(event.file)

      let fileListLen = this[ `fileList${ event.name }` ].length

      lists.map((item) => {
        this[ `fileList${ event.name }` ].push({
          ...item,
          status: 'uploading',
          message: '上传中'
        })
      })
      for (let i = 0; i < lists.length; i++) {
        let result = await this.uploadFilePromise(lists[ i ].url)

        result = JSON.parse(result)
        console.log(result)
        this.picUrl = 'http://skillgo.cn/chargePics/' + result.data

        this.$emit('sendimage', { pic: this.picUrl })

        const item = this[ `fileList${ event.name }` ][ fileListLen ]

        this[ `fileList${ event.name }` ].splice(fileListLen, 1, Object.assign(item, {
          status: 'success',
          message: '',
          url: result
        }))
        fileListLen++
      }
    },
    /**
     * 图片发送
     */
    imageSend() {

    },
    uploadFilePromise(url) {
      const that = this

      return new Promise((resolve,) => {
        const a = uni.uploadFile({
          url: 'https://skillgo.cn/test/shopping/uploadPicture', // 仅为示例，非真实的接口地址
          filePath: url,
          name: 'file',
          header: {
            'content-type': 'multipart/form-data',
            'token': getToken()
          },
          success: (res) => {

            resolve(res.data)
          },
          error: (res) => {

          }
        })
      })
    },
  }

}
</script>
<style lang="scss">
.sg-choose-image{
  background: #fff;
  padding-bottom: 50rpx;
  .btn{

    button{
      width: 150rpx;
      height: 80rpx;
      border-radius: 40rpx;

      background: rgba(58, 98, 233, 1);
      align-items: right;
      float: right;
      margin-right: 20rpx;
      margin-bottom: 50rpx;
    }
  }
}
</style>
